package com.jhd.fuzhou.view.monitoring;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.jhd.fuzhou.service.AlarmService;
import com.jhd.fuzhou.util.DateTime;
import com.jhd.fuzhou.util.DeleteUnuseZero;
import com.jhd.fuzhou.util.UtilHelper;
import com.jhd.fuzhou.view.login.BaseActivity;
import com.jhd.fuzhou.R;
import com.jhd.fuzhou.vo.AlarmDataVo;
import com.jhd.fuzhou.vo.JsonForResult;
import com.jhd.fuzhou.vo.SearchUnit;

import net.zigin.commons.util.StringUtil;

import java.sql.Date;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

import static com.jhd.fuzhou.util.TimeUtil.getTimeDialog5;
/*原在线监测，改监测预警*/
public class OnlineMonitoringActivity extends BaseActivity {

    @BindView(R.id.recyclerView)RecyclerView recyclerView;
    private ProgressDialog _dialog;
    private Context context=this;
    private LinearLayoutManager layoutManager;
    @BindView(R.id.tv_loading)TextView tv_loading;
    @BindView(R.id.iv_cancel)ImageView iv_cancel;
    @BindView(R.id.et_search)EditText et_search;
    private SearchUnit searchUnit;
    private List<AlarmDataVo> alarmDataVoList=new ArrayList<>();
    private AlarmDataVoAdapter alarmDataVoAdapter;
    private AlertDialog _alertDialog;
    private RecyclerView rv_monitor_type;
    private String[] typeNameList=new String[]{"空气","辐射","泳池水","饮用水"};
    private String[] typeIdList=new String[]{"01","02","03","04"};
    private String typeId;

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_online_monitoring);
    }

    @Override
    protected void processLogic() {
        onBack();
        _dialog = new ProgressDialog(context);
        searchUnit=new SearchUnit();
        searchUnit.setPageIndex(1);
        searchUnit.setPageNum(1);//默认只有一页
        searchUnit.setKeyword(et_search.getText().toString());
        searchUnit.setStartTime(DateTime.getTodayStart());
        searchUnit.setEndTime(DateTime.getTodayEnd());
        layoutManager = new LinearLayoutManager(context);
        recyclerView.setLayoutManager(layoutManager);
        getAlarmDataPage();
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int lastCompletelyVisibleItemPosition = layoutManager.findLastCompletelyVisibleItemPosition();
                if(lastCompletelyVisibleItemPosition==layoutManager.getItemCount()-1){
                    tv_loading.setVisibility(View.VISIBLE);
                    searchUnit.setPageIndex(searchUnit.getPageIndex()+1);
                    if(searchUnit.getPageIndex()<=searchUnit.getPageNum()){
                        tv_loading.setText(getString(R.string.loading));
                        getAlarmDataPage();
                    }else{
                        tv_loading.setText(getString(R.string.arrival_bottom));
                    }
                }else{
                    tv_loading.setVisibility(View.GONE);//没到底部，隐藏
                }
            }
        });
        et_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                searchUnit.setPageIndex(1);
                searchUnit.setKeyword(et_search.getText().toString());
                alarmDataVoList.clear();
                getAlarmDataPage();
                return false;//当这里返回的为false时，表示还能再进行其他操作
            }
        });
        et_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) { }
            @Override
            public void afterTextChanged(Editable s) {
                if(s.toString().equals("")){
                    searchUnit.setPageIndex(1);
                    searchUnit.setKeyword("");
                    alarmDataVoList.clear();
                    getAlarmDataPage();
                    iv_cancel.setVisibility(View.GONE);
                }else{
                    iv_cancel.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    @OnClick({R.id.iv_cancel,R.id.lin_select})
    public void onClick(View v){
        switch (v.getId()){
            case R.id.iv_cancel:
                et_search.setText("");
                iv_cancel.setVisibility(View.GONE);
                break;
            case R.id.lin_select:
                dialogShow();
                break;
        }
    }
    /*设置有无整改*/
    public void setTypeButton(RecyclerView recyclerView){
        GridLayoutManager layoutManage = new GridLayoutManager(context, 2);
        recyclerView.setLayoutManager(layoutManage);
        TypeAdapter recyclerAdapter=new TypeAdapter();
        recyclerView.setAdapter(recyclerAdapter);
    }
    public class TypeAdapter extends RecyclerView.Adapter<TypeAdapter.ViewHolder> {
        private int checkPosition=-1;//默认选中全部
        @NonNull
        @Override
        public TypeAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_radio, parent, false);
            TypeAdapter.ViewHolder viewHolder = new TypeAdapter.ViewHolder(itemView);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull TypeAdapter.ViewHolder holder, int position) {
            holder.rb_radio.setText(typeNameList[position]);
            holder.rb_radio.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    checkPosition=position;
                    typeId=typeIdList[checkPosition];
                    notifyDataSetChanged();
                }
            });
            if(position==checkPosition){
                holder.rb_radio.setChecked(true);
            }else{
                holder.rb_radio.setChecked(false);
            }
        }

        @Override
        public int getItemCount() {
            return typeNameList.length;
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            RadioButton rb_radio;
            public ViewHolder(View itemView) {
                super(itemView);
                this.rb_radio = itemView.findViewById(R.id.rb_radio);
            }
        }
    }

    //点击筛选，跳弹窗
    public void dialogShow() {
        LayoutInflater mLayoutInflater = LayoutInflater.from(this);
        View view = mLayoutInflater.inflate(R.layout.dialog_online_screen, null);
        final AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context, R.style.ActionSheetDialogStyle);
        alertBuilder.setView(view);
        _alertDialog = alertBuilder.create();
        //获取当前Activity所在的窗体
        Window window = _alertDialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        _alertDialog.show();
        EditText et_search_dialog = (EditText) view.findViewById(R.id.et_search);
        ImageView iv_cancel_dialog = (ImageView) view.findViewById(R.id.iv_cancel);
        TextView tv_startTime = (TextView) view.findViewById(R.id.tv_startTime);
        TextView tv_endTime = (TextView) view.findViewById(R.id.tv_endTime);
        ImageView iv_dismiss = (ImageView) view.findViewById(R.id.iv_dismiss);
        Button btn_reset = (Button) view.findViewById(R.id.btn_reset);
        Button btn_confirm = (Button) view.findViewById(R.id.btn_confirm);
        rv_monitor_type = (RecyclerView) view.findViewById(R.id.rv_monitor_type);
        setTypeButton(rv_monitor_type);
        tv_startTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getTimeDialog5(tv_startTime,view.getContext());
            }
        });
        tv_endTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getTimeDialog5(tv_endTime,view.getContext());
            }
        });
        btn_reset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                typeId=null;et_search_dialog.setText("");
                tv_endTime.setText("结束时间");
                tv_startTime.setText("开始时间");
                searchUnit.setStartTime(DateTime.getTodayStart());
                searchUnit.setEndTime(DateTime.getTodayEnd());
                searchUnit.setEndTime(null);
                searchUnit.setKeyword(null);
                setTypeButton(rv_monitor_type);
            }
        });
        btn_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                _alertDialog.dismiss();
                String startTime=tv_startTime.getText().toString();
                String endTime=tv_endTime.getText().toString();
                searchUnit.setPageIndex(1);
                searchUnit.setKeyword(et_search_dialog.getText().toString());
                searchUnit.setEquipmentType(typeId);
                searchUnit.setStartTime(("开始时间".equals(startTime))?DateTime.getTodayStart():startTime);
                searchUnit.setEndTime(("结束时间".equals(endTime))?DateTime.getTodayEnd():endTime);
                alarmDataVoList.clear();
                getAlarmDataPage();
            }
        });
        iv_dismiss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                _alertDialog.dismiss();
            }
        });
        iv_cancel_dialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                et_search_dialog.setText("");
                iv_cancel_dialog.setVisibility(View.GONE);
            }
        });
        et_search_dialog.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) { }
            @Override
            public void afterTextChanged(Editable s) {
                if(!s.toString().equals("")){
                    iv_cancel_dialog.setVisibility(View.VISIBLE);
                }else{
                    iv_cancel_dialog.setVisibility(View.GONE);
                }
            }
        });
        WindowManager.LayoutParams params = window.getAttributes() ;
        params.width =(int) (getWindowManager().getDefaultDisplay().getWidth());                     //使用这种方式更改了dialog的框宽
        window.setAttributes(params);
    }

    private void getAlarmDataPage() {
        if(!_dialog.isShowing()){
            _dialog.setMessage("正在获取在线监督列表,请稍等...");
            _dialog.show();
        }
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        AlarmService vs = retrofit.create(AlarmService.class);
        Map<String, Object> params = new LinkedHashMap<String, Object>();
        params.put("pageIndex", searchUnit.getPageIndex());
        params.put("pageSize", 20);
        params.put("alarmType", 1);
        if(!StringUtil.isNullOrEmpty(searchUnit.getKeyword()))params.put("query",searchUnit.getKeyword() );//模糊查询
        if(!StringUtil.isNullOrEmpty(searchUnit.getEquipmentType()))params.put("equipmentType",searchUnit.getEquipmentType());
        if(!StringUtil.isNullOrEmpty(searchUnit.getStartTime()))params.put("startTime",searchUnit.getStartTime());
        if(!StringUtil.isNullOrEmpty(searchUnit.getEndTime()))params.put("endTime",searchUnit.getEndTime());
        RequestBody requestBody = RequestBody.create(MediaType.parse("Content-Type, application/json"), JSON.toJSONString(params));
        Call<JsonForResult> jsonForResultCall = vs.getAlarmDataPage(application.getAccessToken(),requestBody);//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                if(_dialog != null)_dialog.cancel();
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if (jsonForResult.getData() != null) {
                            List<AlarmDataVo> alarmDataVos = JSON.parseArray(jsonForResult.getData().toString(), AlarmDataVo.class);
                            for (AlarmDataVo alarmDataVo : alarmDataVos) {
                                alarmDataVoList.add(alarmDataVo);
                            }
                            if (searchUnit.getPageIndex() == 1) {
                                alarmDataVoAdapter = new AlarmDataVoAdapter();
                                recyclerView.setAdapter(alarmDataVoAdapter);
                            } else {
                                tv_loading.setVisibility(View.GONE);
                                alarmDataVoAdapter.notifyDataSetChanged();
                            }
                            searchUnit.setPageNum(jsonForResult.getTotal()/20+1);
                        } else {
                            alarmDataVoAdapter = new AlarmDataVoAdapter();
                            recyclerView.setAdapter(alarmDataVoAdapter);
                            tv_loading.setText(context.getString(R.string.arrival_bottom));
                        }
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    if(_dialog != null)_dialog.cancel();
//                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                if(_dialog != null)_dialog.cancel();
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg;
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
    private class AlarmDataVoAdapter extends RecyclerView.Adapter<AlarmDataVoAdapter.ViewHolder> {
        @Override
        public AlarmDataVoAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_online_monitor, parent, false);
            AlarmDataVoAdapter.ViewHolder viewHolder = new AlarmDataVoAdapter.ViewHolder(itemView);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull AlarmDataVoAdapter.ViewHolder holder, int position) {
            String ss=DeleteUnuseZero.convertByPattern(String.valueOf(alarmDataVoList.get(position).getOriginValue()));
            holder.tv_originValue.setText((ss==null)?"":ss);
            holder.tv_itemUnit.setText(StringUtil.isNullOrEmpty(alarmDataVoList.get(position).getItemUnit())?"":alarmDataVoList.get(position).getItemUnit());
            holder.tv_monitor_name.setText(StringUtil.isNullOrEmpty(alarmDataVoList.get(position).getEquipmentName())?"":alarmDataVoList.get(position).getEquipmentName());
            holder.tv_monitor_time.setText(StringUtil.isNullOrEmpty(alarmDataVoList.get(position).getCreateTime())?"":alarmDataVoList.get(position).getCreateTime());
            holder.tv_monitor_address.setText(StringUtil.isNullOrEmpty(alarmDataVoList.get(position).getSupervisedUnitName())?"":alarmDataVoList.get(position).getSupervisedUnitName());
            String monitorItem=alarmDataVoList.get(position).getMonitorItem();
            if("01".equals(alarmDataVoList.get(position).getMonitorItem())){
                holder.iv_type.setImageResource(R.mipmap.ic_co2);
            }else if("02".equals(alarmDataVoList.get(position).getMonitorItem())){
                holder.iv_type.setImageResource(R.mipmap.ic_pm25);
            }else if("03".equals(alarmDataVoList.get(position).getMonitorItem())){
                holder.iv_type.setImageResource(R.mipmap.ic_voc);
            }else if("04".equals(alarmDataVoList.get(position).getMonitorItem())){
                holder.iv_type.setImageResource(R.mipmap.ic_hcho);
            }else if("05".equals(alarmDataVoList.get(position).getMonitorItem())){
                holder.iv_type.setImageResource(R.mipmap.ic_co);
            }else if("06".equals(alarmDataVoList.get(position).getMonitorItem())){
                holder.iv_type.setImageResource(R.mipmap.ic_pm);
            }else if("07".equals(alarmDataVoList.get(position).getMonitorItem())){//辐射
                holder.iv_type.setImageResource(R.mipmap.ic_sv);
            }else if("08".equals(alarmDataVoList.get(position).getMonitorItem())||"15".equals(alarmDataVoList.get(position).getMonitorItem())){
                holder.iv_type.setImageResource(R.mipmap.ic_cl);
            }else if("09".equals(alarmDataVoList.get(position).getMonitorItem())||"18".equals(alarmDataVoList.get(position).getMonitorItem())){
                holder.iv_type.setImageResource(R.mipmap.ic_temperature);
            }else if("10".equals(alarmDataVoList.get(position).getMonitorItem())||"17".equals(alarmDataVoList.get(position).getMonitorItem())){
                holder.iv_type.setImageResource(R.mipmap.ic_ph);
            }else if("11".equals(alarmDataVoList.get(position).getMonitorItem())){
                holder.iv_type.setImageResource(R.mipmap.ic_do);
            }else if("12".equals(alarmDataVoList.get(position).getMonitorItem())){
                holder.iv_type.setImageResource(R.mipmap.ic_ddl);
            }else if("13".equals(alarmDataVoList.get(position).getMonitorItem())||"16".equals(alarmDataVoList.get(position).getMonitorItem())){
                holder.iv_type.setImageResource(R.mipmap.ic_zd);
            }else if("14".equals(alarmDataVoList.get(position).getMonitorItem())){
                holder.iv_type.setImageResource(R.mipmap.ic_n);
            }
            if(alarmDataVoList.get(position).getAlarmLevel()==1){
                holder.tv_status.setBackgroundResource(R.drawable.above_background);
                holder.tv_status.setText("红色预警");
            }else if(alarmDataVoList.get(position).getAlarmLevel()==2){
                holder.tv_status.setBackgroundResource(R.drawable.orange_background);
                holder.tv_status.setText("黄色预警");
            }
            holder.linearLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(context, OnlineMonitorDetailActivity.class);
                    //加入参数，传递给AnotherActivity
                    Gson gson = new Gson();
                    intent.putExtra("data", gson.toJson(alarmDataVoList.get(position)));
                    startActivity(intent);
                }
            });
        }

        @Override
        public int getItemCount() {
            return alarmDataVoList.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            TextView tv_originValue, tv_itemUnit, tv_monitor_name, tv_monitor_address,tv_monitor_time,tv_status;
            LinearLayout linearLayout;ImageView iv_type;

            public ViewHolder(View itemView) {
                super(itemView);
                this.tv_originValue = itemView.findViewById(R.id.tv_originValue);
                this.tv_itemUnit = itemView.findViewById(R.id.tv_itemUnit);
                this.tv_monitor_name = itemView.findViewById(R.id.tv_monitor_name);
                this.tv_status = itemView.findViewById(R.id.tv_status);
                this.tv_monitor_address = itemView.findViewById(R.id.tv_monitor_address);
                this.tv_monitor_time = itemView.findViewById(R.id.tv_monitor_time);
                this.iv_type = itemView.findViewById(R.id.iv_type);
                this.linearLayout = itemView.findViewById(R.id.linearLayout);
            }
        }
    }
}